package com.scpii.api.service.common.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.scpii.api.common.Constants;
import com.scpii.api.domain.common.Field;
import com.scpii.api.domain.ec.Address;
import com.scpii.api.domain.user.Users;
import com.scpii.api.persistence.common.FieldMapper;
import com.scpii.api.persistence.ec.AddressMapper;
import com.scpii.api.persistence.user.UserLinksMapper;
import com.scpii.api.persistence.user.UsersMapper;
import com.scpii.api.service.common.FieldService;
import com.scpii.api.util.PrincipalUtil;

@Service
public class FieldServiceImpl implements FieldService {

	@Resource
	private FieldMapper fieldMapper;

	@Resource
	private UsersMapper usersMapper;

	@Resource
	private UserLinksMapper userLinksMapper;

	@Resource
	private AddressMapper addressMapper;

	@Override
	public List<Field> selectAppExpandField(Long appId, Long categoriesId,
			Integer status) {
		return fieldMapper.selectAppExpandField(appId, categoriesId, status);
	}

	@Override
	public List<Field> selectUserEditInfo(Long appId, Long userId,
			Long categoriesId, Integer status) {
		Users users = usersMapper.selectByPrimaryKey(PrincipalUtil
				.getPrincipal().getId());
		String[] providers = userLinksMapper.selectUserLinkStatus(PrincipalUtil
				.getPrincipal().getId(), Constants.WEIBO_KEY_ARRAY);
		List<Field> result = new ArrayList<Field>();
		Field avatar = new Field(Field.AVATAR.getName(),
				Field.AVATAR.getAliasName(), Field.AVATAR.getMask(),
				Field.AVATAR.getMetaType(), users.getAvatar());
		avatar.setValueStr(users != null ? users.getAvatar() : null);
		result.add(avatar);
		List<Field> fields = fieldMapper.selectUserEditInfo(appId,
				categoriesId, userId, status);
		Map<String, String> fieldUserValues = usersMapper.selectByColumns(
				Field.FIELD_USER_KEYS, PrincipalUtil.getPrincipal().getId());
		if (fields != null && fields.size() != 0) {
			for (Field field : fields) {
				String fieldName = field.getName();
				String keyValue = Field.FIELD_USER_KEY.get(fieldName);
				if (keyValue != null) {
					field.setValueStr(fieldUserValues.get(keyValue));
				}
				if ("地址".equals(fieldName)) {
					Address persistAddress = addressMapper
							.selectByPrimaryKey(users.getAddressId());
					field.setValueStr(persistAddress != null ? persistAddress
							.getAddressLine() : null);
				}
			}
			CollectionUtils.addAll(result, fields.toArray());
		}
		Field weibo = new Field(Field.WEIBO.getName(),
				Field.WEIBO.getAliasName(), Field.WEIBO.getMask(),
				Field.WEIBO.getMetaType(), providers);
		result.add(weibo);
		return result;
	}

	@Override
	public Long[] selectRequiredIdsNotFillIn(Long targetId, Integer status) {
		return fieldMapper.selectRequiredIdsNotFillIn(targetId, status);
	}
}
